package com.shire.shire_interface.filter;

import com.shire.shire_interface.common.utils.RequestHelper;
import com.shire.shire_interface.common.utils.StrUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private byte[] body = null;


    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        try {
            String encoding = "";
            if(StrUtils.getNullStr(request.getHeader("content-encoding")).indexOf("gzip")>=0){
                encoding = "gzip";
            }
            String bodyString = RequestHelper.getBodyString(request, encoding);
            body = bodyString.getBytes(Charset.forName("UTF-8"));
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}
